package com.yoda.mall.admin.advice;

import com.yoda.common.Status;
import com.yoda.common.exception.BusinessException;
import com.yoda.common.exception.ErrorResult;
import com.yoda.mall.model.vo.R;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.ParseException;


/**
 * @author shawn
 * @date 2022年 12月 16日 18:45
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.yoda.mall.admin.controller")
public class MallExceptionAdvice{

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R ValidatorExceptionHandler(MethodArgumentNotValidException m){
        log.error("数据校验出现问题{}，异常类型：{}",m.getMessage(),m.getClass());
        BindingResult bindingResult = m.getBindingResult();

        StringBuilder message = new StringBuilder();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            message.append(fieldError.getDefaultMessage()).append(",");
        });
        message.deleteCharAt(message.lastIndexOf(",")).append(";");
        return R.error(String.valueOf(message), Status.VERIFY_ERR.getCode());
    }

    @ExceptionHandler(value = JwtException.class)
    public R expiredJwtException(JwtException ee){
        log.error("捕获到token解析异常!");
        ee.printStackTrace();
        return R.error(ErrorResult.tokenError().getErrMessage(),ErrorResult.tokenError().getErrCode());
    }
    @ExceptionHandler(value = ParseException.class)
    public R parseExceptionHandler(ParseException ee){
        log.error("捕获到日期解析异常!");
        ee.printStackTrace();
        return R.error(ErrorResult.dateParseError().getErrMessage(),ErrorResult.dateParseError().getErrCode());
    }

    @ExceptionHandler(value = BusinessException.class)
    public R businessExceptionHandler(BusinessException be){
        log.error("捕获到业务异常!");
        be.printStackTrace();
        return R.error(be.getErrorResult().getErrMessage(),be.getErrorResult().getErrCode());
    }

    @ExceptionHandler(value = Throwable.class)
    public R unKnowException(Throwable ee){
        log.error("捕获到未知异常!");
        ee.printStackTrace();
        return R.error(ErrorResult.error().getErrMessage(),ErrorResult.error().getErrCode());
    }
}
